﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace SearchApp
{

    public partial class Form1 : Form
    {
        private readonly HttpClient _httpClient;

        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源，为 true；否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        public Form1()
        {
            InitializeComponent();
            _httpClient = new HttpClient();
        }

        //异步编程
        private async void BtnSearch_Click(object sender, EventArgs e)
        {
            string keyword = txtKeyword.Text;
            if (string.IsNullOrWhiteSpace(keyword))
            {
                MessageBox.Show("请输入要搜索的关键字。");
                return;
            }

            Task<string> baiduTask = SearchBaiduAsync(keyword);
            Task<string> bingTask = SearchBingAsync(keyword);

            // 使用await等待两个任务完成
            await Task.WhenAll(baiduTask, bingTask);
            // 显示结果
            txtBaiduResult.Text = baiduTask.Result;
            txtBingResult.Text = bingTask.Result;
        }


        private async Task<string> SearchBaiduAsync(string keyword)
        {
            try
            {
                // 构造百度搜索的URL，使用Uri.EscapeDataString对关键字进行编码
                string uri = $"https://www.baidu.com/s?wd={Uri.EscapeDataString(keyword)}";

                // 清空HttpClient的默认请求头
                _httpClient.DefaultRequestHeaders.Clear();

                // 添加模拟浏览器的请求头
                _httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
                //_httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
                //_httpClient.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
                //_httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");

                // 发送GET请求到构造的URL
                HttpResponseMessage response = await _httpClient.GetAsync(uri);

                // 确保响应状态码为成功（200 OK）
                response.EnsureSuccessStatusCode();

                // 异步读取响应内容为字符串
                string responseBody = await response.Content.ReadAsStringAsync();

                // 从HTML响应内容中提取纯文本
                string result = ExtractTextFromHtml(responseBody);

                // 返回前200个字符的文本，如果结果长度小于200则返回整个结果
                return result.Length > 200 ? result.Substring(0, 200) : result;
            }
            catch (HttpRequestException e)
            {
                // 如果请求过程中发生错误，记录错误信息并返回错误消息
                Console.WriteLine($"请求百度时发生错误: {e.Message}");
                return $"请求百度时发生错误: {e.Message}";
            }
        }

        private async Task<string> SearchBingAsync(string keyword)
        {
            try
            {
                // 构造必应搜索的URL，使用Uri.EscapeDataString对关键字进行编码
                string uri = $"https://api.bing.microsoft.com/v7.0/search?q={Uri.EscapeDataString(keyword)}";

                // 清空HttpClient的默认请求头
                _httpClient.DefaultRequestHeaders.Clear();

                // 添加模拟浏览器的请求头和必应API密钥
                _httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
                //_httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "YOUR_BING_API_KEY");

                // 发送GET请求到构造的URL
                HttpResponseMessage response = await _httpClient.GetAsync(uri);

                // 确保响应状态码为成功（200 OK）
                response.EnsureSuccessStatusCode();

                // 异步读取响应内容为字符串
                string responseBody = await response.Content.ReadAsStringAsync();

                // 解析JSON响应内容
                BingSearchResponse bingResponse = JsonConvert.DeserializeObject<BingSearchResponse>(responseBody);
                string result = string.Join(" ", bingResponse.WebPages.Value.Select(page => page.Snippet));


                // 返回前200个字符的文本，如果结果长度小于200则返回整个结果
                return result.Length > 200 ? result.Substring(0, 200) : result;
            }
            catch (HttpRequestException e)
            {
                // 如果请求过程中发生错误，记录错误信息并返回错误消息
                Console.WriteLine($"请求必应时发生错误: {e.Message}");
                return $"请求必应时发生错误: {e.Message}";
            }
        }

        // 提取HTML中的文字内容
        private string ExtractTextFromHtml(string html)
        {
            // 使用正则表达式去除HTML标签
            string result = Regex.Replace(html, @"<[^>]+>", "").Trim();
            return result;
        }

        private void BtnReset_Click(object sender, EventArgs e)
        {
            // 清空关键字和搜索结果
            txtKeyword.Clear();
            txtBaiduResult.Clear();
            txtBingResult.Clear();
        }

        private void BtnCopyBaidu_Click(object sender, EventArgs e)
        {
            // 将百度搜索结果复制到剪贴板
            if (!string.IsNullOrWhiteSpace(txtBaiduResult.Text))
            {
                Clipboard.SetText(txtBaiduResult.Text);
                MessageBox.Show("百度搜索结果已复制到剪贴板。");
            }
            else
            {
                MessageBox.Show("百度搜索没有结果可复制。");
            }
        }

        private void BtnCopyBing_Click(object sender, EventArgs e)
        {
            // 将必应搜索结果复制到剪贴板
            if (!string.IsNullOrWhiteSpace(txtBingResult.Text))
            {
                Clipboard.SetText(txtBingResult.Text);
                MessageBox.Show("必应搜索结果已复制到剪贴板。");
            }
            else
            {
                MessageBox.Show("必应搜索没有结果可复制。");
            }
        }
        // 定义必应搜索响应的类
        public class BingSearchResponse
        {
            public WebPagesResponse WebPages { get; set; }
        }

        public class WebPagesResponse
        {
            public List<BingSearchResult> Value { get; set; }
        }

        public class BingSearchResult
        {
            public string Snippet { get; set; }
        }
    }
}


